﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XTeam.Document.Entities;
using XTeam.Document.Factory.DataAccessInterface;
using XTeam.Core.Helper;
using XTeam.Core.Abstract;
using System.Data.Entity;

namespace XTeam.Documents.DataAccess
{
    public class ArticleClassifyDataAccess : DbCore, IArticleClassifyDataAccess
    {

        public ArticleClassifyDataAccess()
        {


        }

        public override int Append<T>(IList<T> entities)
        {

            int result = 0;
            var db = (DataBase)this.CreateDb();
            using (db)
            {
                var classifyList = base.Search<ArticleClassifyEntity>(null).ToList();
                foreach (var item in entities)
                {
                    var entity = item as ArticleClassifyEntity;
                    entity.ParentId = entity.ParentId <= 0 ? 0 : entity.ParentId;
                    entity.ClassId = -1;

                    var parent = classifyList.SingleOrDefault(i => i.ClassId == entity.ParentId);

                    if (entity.ParentId > 0 && parent == null)
                    {
                        throw new Exception("父类不存在");
                    }
                    db.ArticleClassifyTable.Add(entity);
                    classifyList.Add(entity);
                    result += db.SaveChanges();
                }

                TreeBuilder<ArticleClassifyEntity> tree = new TreeBuilder<ArticleClassifyEntity>(new ArticleClassifyEntity());

                tree.Builder(classifyList);
                db.SaveChanges();
            }
            return result;
        }



        protected override DbContext CreateDb()
        {
            return string.IsNullOrEmpty(this._connectionString) ? new DataBase() : new DataBase(_connectionString);
        }
    }
}
